package logger

import (
	"fmt"
	"github.com/sirupsen/logrus"
	"os"
	"sync"
)

var initOnce sync.Once
var delegate logrusDelegate

type logrusDelegate struct {
	log *logrus.Logger
}

func Factory() Logger {
	initOnce.Do(func() {
		if logFilePath, err := os.OpenFile("logs", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666); err != nil {
			_ = fmt.Errorf("Failed to init log: %v \n", err)
			instance := logrus.StandardLogger()
			instance.Level = logrus.InfoLevel
			delegate = logrusDelegate{log: instance}
		} else {
			instance := logrus.StandardLogger()
			instance.Level = logrus.InfoLevel
			instance.Out = logFilePath
			delegate = logrusDelegate{log: instance}
			initialization(logrusDelegate{log: instance})
		}
	})
	return delegate
}

func (ld logrusDelegate) Trace(args ...interface{}) {
	ld.log.Trace(args...)
}

func (ld logrusDelegate) Tracef(format string, args ...interface{}) {
	ld.log.Tracef(format, args...)
}

func (ld logrusDelegate) Debug(args ...interface{}) {
	ld.log.Debug(args...)
}

func (ld logrusDelegate) Debugf(format string, args ...interface{}) {
	ld.log.Debugf(format, args...)
}

func (ld logrusDelegate) Info(args ...interface{}) {
	ld.log.Info(args...)
}

func (ld logrusDelegate) Infof(format string, args ...interface{}) {
	ld.log.Infof(format, args...)
}

func (ld logrusDelegate) Warn(args ...interface{}) {
	ld.log.Warn(args...)
}

func (ld logrusDelegate) Warnf(format string, args ...interface{}) {
	ld.log.Warnf(format, args...)
}

func (ld logrusDelegate) Error(args ...interface{}) {
	ld.log.Error(args...)
}

func (ld logrusDelegate) Errorf(format string, args ...interface{}) {
	ld.log.Errorf(format, args...)
}

func (ld logrusDelegate) Fatal(args ...interface{}) {
	ld.log.Error(args...)
}

func (ld logrusDelegate) Fatalf(format string, args ...interface{}) {
	ld.log.Errorf(format, args...)
}

func (ld logrusDelegate) ReloadRootLevel(level logrus.Level) {
	ld.log.Level = level
}
